package com.hy.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hy.common.dto.CartDTo;
import com.hy.common.enums.ExceptionEnums;
import com.hy.common.exception.XkException;
import com.hy.common.vo.PageResult;
import com.hy.item.mapper.SkuMappr;
import com.hy.item.mapper.SpuDetailMapper;
import com.hy.item.mapper.SpuMapper;
import com.hy.item.mapper.StockMapper;
import com.hy.item.pojo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoosService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapper  spuDetailMapper;
    @Autowired
    CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private SkuMappr skuMappr;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 分页查询商品列表
     * @param page
     * @param rows
     * @param saleable
     * @param key
     * @return
     */
    public PageResult<Spu> querySpuByPage(Integer page, Integer rows, Boolean saleable, String key) {

        //分页,第一个参数是当前页，第二个参数是每页查询的条数
        PageHelper.startPage(page,rows);
        //过滤
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //根据搜索字段title进行模糊查询
        if (StringUtils.isNoneBlank(key)){
            criteria.andLike("title","%"+key+"%");
        }
        //上下架过滤
        if (saleable!=null){
            //第一个参数是表中字段名
            criteria.andEqualTo("saleable",saleable);

        }
        //查询
        List<Spu> spus = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(spus)){
            throw new XkException(ExceptionEnums.SPU_NOT_FOND);
        }
        //调用解析分类和品牌名称的方法
        loadCategoryAndBrandName(spus);

        //使用分页助手中的pageInfo解析结果
        PageInfo<Spu> info = new PageInfo<>(spus);

        return new PageResult(info.getTotal(),spus);//返回总页数和查询到的结果

    }
    //解析分类和品牌名称
    private void loadCategoryAndBrandName(List<Spu> spus) {

        for (Spu spu:spus){
            //处理分类名称,通过三个cid查询出分类名称
            List<Category> list = categoryService.queryByIds(Arrays.asList(spu.getCid1(),
                    spu.getCid2(), spu.getCid3()));
            //.stream().ma是jdk8新特性，是将一个对象转换成另一个对象
            List<String> names = list.stream().map(Category::getName).collect(Collectors.toList());
            //将一个集合转换成字符串StringUtils.join第一个参数传集合，第二个参数告诉它以什么分割
            spu.setCname(StringUtils.join(names,"/"));
            //处理品牌名称
            Brand brand = brandService.queryByBrandId(spu.getBrandId());
            spu.setBname(brand.getName());
        }
        //发送mq消息
    }

    /**
     * 新增商品
     * @param spu
     * @return
     */
    @Transactional
    public void saveGoods(Spu spu) {

        //商品的修改
        Spu spu1 = spuMapper.selectByPrimaryKey(spu.getId());
        Stock stock1 = new Stock();
        List<Sku> skus1 = spu.getSkus();
        if (spu1!=null){
            //查出表中所有的数据进行新增
            spuMapper.delete(spu);
            spuDetailMapper.deleteByPrimaryKey(spu.getId());
            Sku sku = new Sku();
            sku.setSpuId(spu.getId());
            skuMappr.delete(sku);
            for (Sku k:skus1){
                if (k.getId()!=null){
                    stock1.setSkuId(k.getId());
                    stockMapper.delete(stock1);
                }
            }
        }
        //=========================================================================
        //新增spu
        spu.setId(null);//自增
        spu.setCreateTime(new Date());
        spu.setLastUpdateTime(new Date());
        spu.setSaleable(true);//默认上架
        spu.setValid(true);//默认有效
        int count = spuMapper.insert(spu);
        if (count!=1){
            throw new XkException(ExceptionEnums.CATEGORY_NOT_FOUND);
        }
        //新增detail
        SpuDetail detail = spu.getSpuDetail();
        detail.setSpuId(spu.getId());//spu插入时会返回一个id,spu.getId得到
        spuDetailMapper.insert(detail);
        //新增sku
        List<Sku> skus = spu.getSkus();
        for (Sku sku:skus){
            sku.setSpuId(spu.getId());
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(new Date());
            int count2 = skuMappr.insert(sku);
            if (count2!=1){
                throw new XkException(ExceptionEnums.CATEGORY_NOT_FOUND);
            }
            //新增库存
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            int count3 = stockMapper.insert(stock);
            if (count3!=1){
                throw new XkException(ExceptionEnums.GOODS_SAVE_ERROR);
            }

        }
        //发送mq消息,消息为商品的id
        amqpTemplate.convertAndSend("item.update",spu.getId());
    }
    /**
     * 根据spuId查询detail
     * @param spuId
     * @return
     */
    public SpuDetail queryDetailById(Long spuId) {

        SpuDetail spuDetail = spuDetailMapper.selectByPrimaryKey(spuId);
        if (spuDetail==null){
            throw new XkException(ExceptionEnums.GOODS_DETAIL_NOT_FOUND);
        }
        return spuDetail;
    }

    /**
     * 根据spuId查询下面的所有的sku
     * @param id
     * @return
     */
    public List<Sku> querySkuById(Long id) {
        Sku sku = new Sku();
        sku.setSpuId(id);
        List<Sku> list = skuMappr.select(sku);
        if (CollectionUtils.isEmpty(list)){
            throw new XkException(ExceptionEnums.CATEGORY_SKU_NOT_FOUND);
        }
        //查询库存
        for (Sku s:list){
            Stock stock = stockMapper.selectByPrimaryKey(s.getId());
            if (stock==null){
                throw new XkException(ExceptionEnums.STOCK_NOT_FOUND);
            }
            s.setStock(stock.getStock());//将查询到的库存再装到sku表中
        }
        return list;
    }

    /**
     * 根据spu中的id查询spu中的信息
     * @param id
     */
    public Spu querySpuById(Long id) {
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu==null){
            throw new XkException(ExceptionEnums.SPU_NOT_FOND);
        }
        //查询sku,上面有写过这querySkuById方法，直接调用即可
        spu.setSkus(querySkuById(id));
        //查询detail
        spu.setSpuDetail(queryDetailById(id));
        return spu;
    }

    /**
     * 根据sku的id集合查询所有的sku
     * @param ids
     * @return
     */
    public List<Sku> querySkuByIds(List<Long> ids) {

        List<Sku> skus = skuMappr.selectByIdList(ids);
        return skus;

    }

    /**
     *减库存
     * @param carts
     */
    public void decreaseStock(List<CartDTo> carts) {

       for (CartDTo cart:carts){
           int count = stockMapper.decreaseStock(cart.getSkuId(), cart.getNum());
           if (count!=1){
               throw new XkException(ExceptionEnums.STOCK_NOT_ENOUGH);
           }

       }

    }
}
